<template>
  <el-card>
    <el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
      <el-form-item label="数据源" prop="datasourceId">
        <el-select v-model="state.queryForm.datasourceId" style="width: 100%" placeholder="请选择数据源"
                   @change="getNewDataList">
          <el-option v-for="ds in state.datasourceList" :key="ds.value" :label="ds.label" :value="ds.value"></el-option>
        </el-select>
      </el-form-item>
      <!--   工程信息修改不需要重新加载表格   -->
      <el-form-item label="工程" prop="projectId">
        <el-select v-model="state.queryForm.projectId" style="width: 100%" placeholder="请选择工程信息">
          <el-option v-for="p in state.projectList" :key="p.value" :label="p.label" :value="p.value"></el-option>
        </el-select>
      </el-form-item>
      <!--   模板组信息修改不需要重新加载表格   -->
      <el-form-item label="模板" prop="templateGroupId">
        <el-select v-model="state.queryForm.templateGroupId" style="width: 100%" placeholder="请选择模板信息">
          <el-option v-for="p in state.templateGroupList" :key="p.value" :label="p.label" :value="p.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="state.queryForm.tableName" placeholder="表名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="getDataList()">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="downloadBatchHandle()">下载代码</el-button>
        </el-form-item>
      </el-form>
    </el-form>
    <el-table v-loading="state.dataListLoading" :data="state.dataList" border style="width: 100%"
              @selection-change="selectionChangeHandle">
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="name" label="表名" header-align="center" align="center"></el-table-column>
      <el-table-column prop="comment" label="表说明" header-align="center" align="center"></el-table-column>
      <el-table-column label="操作" fixed="right" header-align="center" align="center" width="250">
        <template #default="scope">
          <el-button type="primary" link @click="previewHandle(scope.row.name)">预览</el-button>
          <el-button type="primary" link @click="editHandle(scope.row.id)">编辑</el-button>
          <el-button type="primary" link @click="downloadBatchHandle(scope.row.name)">下载代码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        :current-page="state.pageNum"
        :page-sizes="state.pageSizes"
        :page-size="state.pageSize"
        :total="state.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
    >
    </el-pagination>

    <preview ref="previewRef" @refreshDataList="getDataList"></preview>
    <import ref="importRef" @refreshDataList="getDataList"></import>
    <edit ref="editRef" @refreshDataList="getDataList"></edit>
    <generator ref="generatorRef" @refreshDataList="getDataList"></generator>
  </el-card>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import {useCrud} from '@/hooks'
import Edit from './edit.vue'
import Generator from './generator.vue'
import Preview from "./preview.vue";
import {ElMessage} from 'element-plus'
import {useDownloadApi} from '@/api/generator'
import {useDataSourceOptionListApi} from "@/api/datasource";
import {IGeneratorOptions} from "@/types/generator";
import {Option} from "@/types/common";
import {useProjectOptionListApi} from "@/api/project";
import {useTableDefaultDataApi} from "@/api/table";
import {ITableVO} from "@/types/table";
import {useTemplateGroupOptionsApi} from "@/api/templateGroup";

const state: IGeneratorOptions<ITableVO> = reactive({
  createdIsNeed: false,
  dataListUrl: '/generator/v1/table/page',
  queryForm: {
    datasourceId: '',
    projectId: '',
    tableName: '',
    templateGroupId: ''
  },
  // 数据源列表
  datasourceList: [] as Option[],
  // 数据列表，多选项
  dataListSelections: [],
  // 工程信息列表
  projectList: [],
  // 模板组信息
  templateGroupList: []
})

const previewRef = ref()
const editRef = ref()
const generatorRef = ref()

// 预览生成的代码
const previewHandle = (tableName: string) => {
  if (!state.queryForm.datasourceId) {
    ElMessage.warning('请选择生成代码的数据源')
  }
  if (!state.queryForm.projectId) {
    ElMessage.warning('请选择生成代码的工程')
  }
  if (!state.queryForm.templateGroupId) {
    ElMessage.warning('请选择生成代码的模板')
  }
  previewRef.value.init(state.queryForm.datasourceId, state.queryForm.projectId, state.queryForm.templateGroupId, tableName)
}

const editHandle = (id?: number) => {
  editRef.value.init(id)
}

/**
 * 根据表名下载
 * @param tableName
 */
const downloadBatchHandle = (tableName?: string) => {
  const tableIds = state.dataListSelections ? state.dataListSelections : []

  // 表名列表
  const tableNames = tableName ? [tableName] : state.dataList?.filter(value => tableIds.includes(value.id)).map(value => value.name);

  if (tableNames!!.length === 0) {
    ElMessage.warning('请选择生成代码的表')
    return
  }
  if (!state.queryForm.datasourceId) {
    ElMessage.warning('请选择生成代码的数据源')
  }
  if (!state.queryForm.projectId) {
    ElMessage.warning('请选择生成代码的工程')
  }
  if (!state.queryForm.templateGroupId) {
    ElMessage.warning('请选择生成代码的模板')
  }
  useDownloadApi({
    datasourceId: state.queryForm.datasourceId,
    projectId: state.queryForm.projectId,
    templateGroupId: state.queryForm.templateGroupId,
    tableNames: tableNames!!.join(',')
  })
}

/**
 * 获取全部数据源列表
 */
const getDataSourceOptionList = async () => {
  useDataSourceOptionListApi().then(res => {
    state.datasourceList = res.data
  })
}

/**
 * 获取全部工程列表
 */
const getProjectOptionList = async () => {
  useProjectOptionListApi().then(res => {
    state.projectList = res.data
  })
}

/**
 * 获取全部模板组列表
 */
const getTemplateGroupOptionList = async () => {
  useTemplateGroupOptionsApi().then(res => {
    state.templateGroupList = res.data
  })
}

/**
 * 获取新的数据
 */
const getNewDataList = () => {
  // 数据源不为空
  if (state.queryForm.datasourceId) {
    getDataList()
  }
}

/**
 * 获取表格默认的数据源
 */
const getTableDefaultData = async () => {
  useTableDefaultDataApi().then(res => {
    const data = res.data
    // 设置默认的数据源
    state.queryForm.datasourceId = data.datasourceId
    // 设置默认的工程 ID
    state.queryForm.projectId = data.projectId
    // 设置默认的组 ID
    state.queryForm.templateGroupId = data.templateGroupId
    // 根据数据列表
    getNewDataList()
  })
}

onMounted(() => {
  // 获取数据源列表
  getDataSourceOptionList()
  // 获取工程列表
  getProjectOptionList()
  // 获取模板组列表
  getTemplateGroupOptionList()
  // 获取默认的数据选项
  getTableDefaultData()
})

const {getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle} = useCrud(state)
</script>
